<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/dute_favicon_32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/dute_favicon_16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <link rel="manifest" href="/images/manifest.json">
  <meta name="msapplication-config" content="/images/browserconfig.xml">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">
  <meta name="google-site-verification" content="mpI5dkydstZXl6UcDCppqktXK0bbvqdZ6LkZ3KNk4Iw">
  <meta name="baidu-site-verification" content="code-a1LksZX2Ds">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"whitestore.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="JVM运行时分区溢出学习JVM必须掌握的一块内容">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解JVM - 分区是如何溢出的？">
<meta property="og:url" content="https://whitestore.top/2022/02/20/yichu/index.html">
<meta property="og:site_name" content="爱看书的阿东">
<meta property="og:description" content="JVM运行时分区溢出学习JVM必须掌握的一块内容">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210804221608.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210805140308.png">
<meta property="article:published_time" content="2022-02-19T16:20:00.000Z">
<meta property="article:modified_time" content="2023-07-16T06:28:09.269Z">
<meta property="article:author" content="阿东">
<meta property="article:tag" content="Jim">
<meta property="article:tag" content="溢出">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210804221608.png">

<link rel="canonical" href="https://whitestore.top/2022/02/20/yichu/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深入理解JVM - 分区是如何溢出的？ | 爱看书的阿东</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="爱看书的阿东" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">爱看书的阿东</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">赐他一块白色石头，石头上写着新名</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>站点地图</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://whitestore.top/2022/02/20/yichu/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="阿东">
      <meta itemprop="description" content="随遇而安">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱看书的阿东">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入理解JVM - 分区是如何溢出的？
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-02-20 00:20:00" itemprop="dateCreated datePublished" datetime="2022-02-20T00:20:00+08:00">2022-02-20</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-07-16 14:28:09" itemprop="dateModified" datetime="2023-07-16T14:28:09+08:00">2023-07-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JVM/" itemprop="url" rel="index"><span itemprop="name">JVM</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2022/02/20/yichu/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2022/02/20/yichu/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>10k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>9 分钟</span>
            </span>
            <div class="post-description">JVM运行时分区溢出学习JVM必须掌握的一块内容</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="深入理解JVM-分区是如何溢出的？"><a href="#深入理解JVM-分区是如何溢出的？" class="headerlink" title="深入理解JVM - 分区是如何溢出的？"></a>深入理解JVM - 分区是如何溢出的？</h1><h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>​    JVM运行时分区溢出学习JVM必须掌握的一块内容，同时由于JVM的升级换代，JVM的内部分区也在逐渐的变化，比如方法区的实现由永久代改为了元空间这些内容都是需要掌握的，这一节将会是一篇关于JVM分区溢出的总结，同样根据两个案例来说下如何排查JVM令人头痛的OOM问题。</p>
<h1 id="前文回顾："><a href="#前文回顾：" class="headerlink" title="前文回顾："></a>前文回顾：</h1><p>​    上一期主要是对JVM调优以及工具的使用做了一个专栏的阶段总结，这里不再赘述，可以看个人主页的历史文章。</p>
<h1 id="概述："><a href="#概述：" class="headerlink" title="概述："></a>概述：</h1><ol>
<li>用图解的方式了解哪些分区会存在分区溢出的问题。</li>
<li>如何用代码来模拟出各个分区的溢出。</li>
<li>用两个案例来讲解分区的溢出是如何排查和解决的。</li>
</ol>
<a id="more"></a>

<h1 id="分区结构图简介："><a href="#分区结构图简介：" class="headerlink" title="分区结构图简介："></a>分区结构图简介：</h1><p>​    在了解分区是如何溢出之前，这里先简单画一个JVM的分区运行图：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210804221608.png" alt=""></p>
<p>​    其实这一段代码在专栏开篇已经讲过，这里直接挪用过来，同时标记了会出现溢出的分区，上面的图对应下面这一段代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">OneWeek</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Properties properties = <span class="keyword">new</span> Properties();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        InputStream resourceAsStream = OneWeek.class.getClassLoader().getResourceAsStream("app.properties");</span><br><span class="line">        properties.load(resourceAsStream);</span><br><span class="line">        System.out.println(<span class="string">"load properties user.name = "</span> + properties.getProperty(<span class="string">"user.name"</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    代码非常简单，当然和本文没有什么关系，这里直接跳过。</p>
<p>​    我们可以看到，容易出现方法区溢出的地方通常是这三个：<strong>方法区，JAVA虚拟机栈和JAVA堆</strong>（准确来说是老年代溢出）。这三个分区的溢出也是日常写代码当中很容易出现溢出的情况，结构图的最上方还有一个直接内存，因为这块空间平时可能用不上但是很容易出问题所以也放进来讲解，下面逐个分析他们发生溢出会出现什么情况：</p>
<p>​    <strong>方法区：</strong>由于现代框架普遍使用动态代理+反射，所以方法区通常会产生很多的代理对象，虽然多数情况下spring的bean都是单例的通常不会产生影响，但是遇到一些需要创建大量非单例对象情况（比如并发问题）下就很容易出现方法区的溢出。</p>
<p>​    <strong>虚拟机栈：</strong>这里看到上面的结构图可能会想1M是不是也太小了？其实每一个分配1M对于绝大多数情况下完全够用了，让虚拟机栈溢出也比较简单， 那就是死循环或者无限递归，下文会用代码进行演示。</p>
<p>​    <strong>堆：</strong>用的最多的分区也是最容易出问题的一个分区，堆内存需要配合垃圾收集器一起进行工作，通常情况下堆溢出是由于老年代回收之后还是有很多对象（占满），导致对象无法再继续分配而产生OOM的异常。</p>
<p>​    <strong>直接内存</strong>：由于篇幅有限直接内存是什么东东请同学们自行百度，这一块空间多数和Netty以及NIO等工具打交道的时候会有机会使用到，在这里重点解释下这块区域怎么溢出，只要记住当JVM<strong>申请不到足够的Direct Memory</strong>的时候就会造成直接内存的溢出。</p>
<p>​    会发生溢出的分区都已经被我们找出来了，下面就来介绍一下各自的分区是如何用代码来模拟溢出的。</p>
<h1 id="分区溢出模拟："><a href="#分区溢出模拟：" class="headerlink" title="分区溢出模拟："></a>分区溢出模拟：</h1><h2 id="方法区："><a href="#方法区：" class="headerlink" title="方法区："></a>方法区：</h2><p>​    首先是方法区的空间溢出，这里不介绍过多的概念，上一节也提到了方法区多数情况下是由于动态生成类过多导致方法区产生了溢出，下面用一段代码来模拟：</p>
<p>​    建立项目的步骤这里省略，直接使用IDE简单生成一个Maven的项目即可，首先我们再Pom.xml文件中导入<strong>CGLIB</strong>的依赖，不清楚这个<strong>CGLIB</strong>是什么也没关系，只要简单理解为可以帮助我们生产动态JAVA类的工具即可，即可以不使用手动<code>new</code>的形式实现一个对象的构建：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>cglib<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>cglib<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.3.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>​    下面是具体的测试代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CglibTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Man</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            System.out.println(<span class="string">"走路中。。。。。"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            Enhancer enhancer = <span class="keyword">new</span> Enhancer();</span><br><span class="line">            enhancer.setSuperclass(Man<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">            enhancer.setUseCache(<span class="keyword">true</span>);</span><br><span class="line">            enhancer.setCallback(<span class="keyword">new</span> MethodInterceptor() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object o, Method method, Object[] objects, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">                    <span class="keyword">if</span>(method.getName().equalsIgnoreCase(<span class="string">"run"</span>))&#123;</span><br><span class="line">                        System.out.println(<span class="string">"遇到红绿灯，等待....."</span>);</span><br><span class="line">                        <span class="keyword">return</span> methodProxy.invokeSuper(o, objects);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">return</span> methodProxy.invokeSuper(o, objects);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">            Man man = (Man) enhancer.create();</span><br><span class="line">            man.run();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    这里简单解读一下代码：</p>
<p>​    在代码的第一句，使用<code>while(true)</code>语句构建一个死循环，让内部的代码不断的循环工作。接着我们首先使用下面这段代码初始化一个生成类的API对象，同时设置生成的类的super类是<code>Man.class</code>，也就是说我们只能生产<code>Man</code>这个类的超类，同时我们开启对象缓存，至于有什么作用无需关注。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Enhancer enhancer = <span class="keyword">new</span> Enhancer();</span><br><span class="line">enhancer.setSuperclass(Man<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">enhancer.setUseCache(<span class="keyword">true</span>);</span><br></pre></td></tr></table></figure>

<p>​    接着我们用回调的<strong>匿名钩子函数</strong>，在方法调用之间增加一个拦截方法，在这里我们做的事情是匹配到<strong>run</strong>方法的调用的对象之前做一些我们自定义的操作，比如像下面这样增加一条打印语句：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">enhancer.setCallback(<span class="keyword">new</span> MethodInterceptor() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">intercept</span><span class="params">(Object o, Method method, Object[] objects, MethodProxy methodProxy)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(method.getName().equalsIgnoreCase(<span class="string">"run"</span>))&#123;</span><br><span class="line">            System.out.println(<span class="string">"遇到红绿灯，等待....."</span>);</span><br><span class="line">            <span class="keyword">return</span> methodProxy.invokeSuper(o, objects);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> methodProxy.invokeSuper(o, objects);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>​    接着GCLIB就会通过JDK的动态代理构建代理对象并且完成方法的调用。</p>
<p>​    既然这里可以对于Man对象的方法进行拦截，那对他的子类当然也是同样适用的，我们可以增加一个新的类继承Man类，比如像下面这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">OldMan</span> <span class="keyword">extends</span> <span class="title">Man</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"走的很慢很慢。。。。。。。"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    然后我们在死循环的结尾增加下面的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">OldMan oldMan = (OldMan) enhancer.create();</span><br><span class="line">oldMan.run();</span><br></pre></td></tr></table></figure>

<p>​    紧接着，我们就可以开始运行代码了，然后，然后你会发现程序报错了。。。。。。错误内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">遇到红绿灯，等待.....</span><br><span class="line">走路中。。。。。</span><br><span class="line">Exception in thread <span class="string">"main"</span> java.lang.ClassCastException: com.xd.test.jvm.CglibTest$Man$$EnhancerByCGLIB$$ba733242 cannot be cast to com.xd.test.jvm.CglibTest$OldMan</span><br><span class="line">    at com.xd.test.jvm.CglibTest.main(CglibTest.java:<span class="number">50</span>)</span><br></pre></td></tr></table></figure>

<p>​    这里其实是类强制转换的异常，我们不能把一个动态生成的代理父类转为一个代理的子类，这里要改成下面的格式，利用多态的特性把<code>superclass</code>设置为<code>Man</code>子类即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">enhancer.setSuperclass(OldMan<span class="class">.<span class="keyword">class</span>)</span>;</span><br></pre></td></tr></table></figure>

<p>限制方法区大小：</p>
<p>​    重点来了，现在我们限制一下方法区的大小，这里使用了<strong>JDK8的版本</strong>，参数和JDK8以下的参数不一样，由于JDK8使用了元空间，我们需要使用下面的参数来进行元空间的大小设置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-XX:MetaspaceSize=<span class="number">10</span>m -XX:MaxMetaspaceSize=<span class="number">10</span>m</span><br></pre></td></tr></table></figure>

<p>​    注意<code>MetaspaceSize</code>这个值<strong>不是</strong>初始化元空间大小哦，而是初次触发元空间扩展的大小，而<code>MaxMetaspaceSize</code>才是元空间真正允许扩展的最大大小，虽然默认设置下这两个参数的值都很小，但是JVM会在每次<strong>FULL GC</strong>之后<strong>自动扩大元空间</strong>，理论上来说可以无限接近于系统内存的大小，但是毫无疑问JVM会有限制，在扩展到一定程度之后会直接让方法区溢出，所以在这里这两个参数我们设置为一样的大小即可。</p>
<p>​    接着运行代码，不需要多长时间，控制台就会爆出如下的提示，告诉我们方法去区溢出了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Caused by: java.lang.OutOfMemoryError: Metaspace</span><br></pre></td></tr></table></figure>

<p>​    以上便是方法区的溢出测试。</p>
<h2 id="虚拟机栈："><a href="#虚拟机栈：" class="headerlink" title="虚拟机栈："></a>虚拟机栈：</h2><p>​    虚拟机栈的溢出是最简单的，这里直接上代码演示一下：</p>
<p>​    首先我们需要设置一下栈内存大小，这里我们为每个线程分配<strong>1M</strong>的栈内存大小：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">-XX:ThreadStackSize=<span class="number">1</span>M</span><br></pre></td></tr></table></figure>

<p>​    接着使用下面的代码跑一下，代码内容十分简单就是一个单纯的无限递归调用的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> count = <span class="number">0</span>;</span><br><span class="line">    work(count);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">work</span><span class="params">(<span class="keyword">int</span> count)</span></span>&#123;</span><br><span class="line">    System.out.println(<span class="string">"一共运行了:"</span>+ (count++) +<span class="string">"次"</span>);</span><br><span class="line">    work(count);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    运行结果如下，从个人电脑来看运行了6000多次：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">一共运行了:<span class="number">6466</span>次</span><br><span class="line">一共运行了:<span class="number">6467</span>次</span><br><span class="line">一共运行了:<span class="number">6468</span>次</span><br><span class="line">一共运行了:<span class="number">6469</span>次</span><br><span class="line">一共运行了:<span class="number">6470</span>次</span><br><span class="line">一共运行了:<span class="number">6471</span>次</span><br><span class="line">java.lang.StackOverflowError</span><br><span class="line">	at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:<span class="number">691</span>)</span><br><span class="line">	at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:<span class="number">579</span>)</span><br><span class="line">	at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:<span class="number">271</span>)</span><br><span class="line">	at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:<span class="number">125</span>)</span><br><span class="line">	at java.io.OutputStreamWriter.write(OutputStreamWriter.java:<span class="number">207</span>)</span><br><span class="line">	at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:<span class="number">129</span>)</span><br><span class="line">	at java.io.PrintStream.write(PrintStream.java:<span class="number">526</span>)</span><br><span class="line">	at java.io.PrintStream.print(PrintStream.java:<span class="number">669</span>)</span><br><span class="line">	at java.io.PrintStream.println(PrintStream.java:<span class="number">806</span>)</span><br></pre></td></tr></table></figure>

<p>​    栈内存的溢出比较好理解，多数情况下是由于编程引发的错误，比如循环调用，无限递归调用等等，栈内存溢出的情况比较罕见的，一般是开发人员编程错误（这里也不用担心正常方法调用链过长的可能性）。</p>
<p>​    栈的溢出也可以形象理解为往一个纸箱里面放书，当书放不进纸箱的时候，系统只能报错了，另外特别注意栈帧弹出虚拟机栈之后变量是<strong>直接销毁</strong>的，所以<strong>不存在垃圾回收</strong>这一个概念，再次强调，<strong>虚拟机栈和垃圾回收器没有半毛钱关系。</strong></p>
<p>​    </p>
<h2 id="堆内存："><a href="#堆内存：" class="headerlink" title="堆内存："></a>堆内存：</h2><p>​    堆内存的溢出模拟测试也比较简单，就是不断创建 <strong>无法被垃圾回收器回收的对象</strong>，比如说大字符串，或者占用很多内存的数组，最简单的办法就是分配一个一次性无法容纳下的超大数组，是不是非常简单？下面同样演示一段代码进行讲解：</p>
<p>​    同样，我们需要先给堆空间限制一下大小，使用<code>-Xms20M -Xmx20M</code> 来限制一下堆内存的大小，然后编写下面的代码并且执行：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span>[] arr = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>*<span class="number">1024</span>*<span class="number">20</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>​    运行代码，会获得下面的结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Exception in thread <span class="string">"main"</span> java.lang.OutOfMemoryError: Java heap space</span><br><span class="line">	at Test.main(Test.java:<span class="number">11</span>)</span><br></pre></td></tr></table></figure>

<p>​    上面是模拟溢出的一种最简单的办法，更多的溢出这里不再过多讨论，下面我们来看下一个重点：真实场景下如何排查TOMCAT溢出问题？</p>
<h1 id="如何排查分区溢出问题？"><a href="#如何排查分区溢出问题？" class="headerlink" title="如何排查分区溢出问题？"></a>如何排查分区溢出问题？</h1><h2 id="Tomcat出现OOM如何排查？"><a href="#Tomcat出现OOM如何排查？" class="headerlink" title="Tomcat出现OOM如何排查？"></a>Tomcat出现OOM如何排查？</h2><p>​    在这个案例中，一个每秒仅仅只有<strong>100+请求</strong>的系统却频繁的因为OOM而崩溃，下面会一步步排查一个这样的问题是如何牵扯到Tomcat和分区溢出扯上关系的。</p>
<h3 id="还原案发现场："><a href="#还原案发现场：" class="headerlink" title="还原案发现场："></a>还原案发现场：</h3><p>​    首先，我们需要还原案发现场，在某一天系统突然收到报警，通知说线上系统出了问题。于是排查异常信息，这时候第一件事情是跑到线上看一下日志的结果，结果非常惊讶的发现报错信息如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Exception in thread <span class="string">"http-nio-8080-exec-1089"</span> java.lang.OutOfMemoryError: Java heap space</span><br></pre></td></tr></table></figure>

<p>​    这一段和上面模拟的代码结果非常类似，不同的是这个线程是一个<strong>Tomcat的线程</strong>，当然这个消息非常不好，因为线上居然发生了OOM！这是一个非常严重的BUG。下面来看下是如何一步步进行排查的。</p>
<h3 id="简单了解Tomcat的底层原理"><a href="#简单了解Tomcat的底层原理" class="headerlink" title="简单了解Tomcat的底层原理"></a>简单了解Tomcat的底层原理</h3><p>​    首先我们来简单了解一下Tomcat这种web服务器的工作原理是什么呢？其实学了JVM之后，对这个概念应该有了更深入的了解，毫无疑问就是底层依然还是一个JVM的进程，通常情况下，我们使用Tomcat都会绑定一个8080的端口启动，Tomcat在最开始的时候请求是通过一个叫做Servlet的东西进行处理的，而这个Servlet在后来经过框架的包装就变成了spring mvc的一个<strong>mapping</strong>，到后续随着框架的演进，现在通常都会使用框架比如说spring boot内置的Tomcat进行web服务器的管理，我们不再需要单独的Tomcat进行项目部署操作，直接集成式一键启动即可。</p>
<p>​    那么我们的请求是如何被Tomcat解析的呢？Tomcat通过监听端口并把我们发送过来的网络请求经过解析的和处理，然后再传给MVC的进行包装分发，最后到具体的某一个映射（Mapping），整个业务过程其实就是Tomcat把我们写好的类（controller）通过他的类加载器加载到Tomcat的内部进行执行，执行完成之后再结果返回给请求发送方。</p>
<p>​    那么tomcat是如何监听端口的呢？其实tomcat本身就是一个工作线程，对于我们的每一个请求，tomcat的工作线程都会从自己管理的线程池中分配一个工作线程来负责进行处理，也就是说多个请求之前是相互独立并且互不干扰的。为了更好的理解，下面画了图来简单解释一下上文描述的工作机制：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210805140308.png" alt=""></p>
<blockquote>
<p>小贴士：</p>
<p>建议在JVM调优的时候务必加上此参数：<code>-XX:+HeapDumpOnOutOfMemoryError</code>。一旦出现OOM等内存溢出的情况时候，JVM会从内存中备份一份当前的溢出日志，根据日志也可以很快的定位到问题发生的点以及产生了什么问题。</p>
</blockquote>
<h3 id="内存快照分析："><a href="#内存快照分析：" class="headerlink" title="内存快照分析："></a>内存快照分析：</h3><p>​    言归正传，这里再次回到案例来，这里省略具体的分析步骤，最后通过内存快照的结果发现，导致内存泄露的居然是数组，从日志的分析结果中发现了如下的内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">byte[10008192] @ 0x7aa800000 GET &#x2F;order&#x2F;v2 HTTP&#x2F;1.0-forward...</span><br><span class="line">byte[10008192] @ 0x7aa800000 GET &#x2F;order&#x2F;v2 HTTP&#x2F;1.0-forward...</span><br><span class="line">byte[10008192] @ 0x7aa800000 GET &#x2F;order&#x2F;v2 HTTP&#x2F;1.0-forward...</span><br><span class="line">byte[10008192] @ 0x7aa800000 GET &#x2F;order&#x2F;v2 HTTP&#x2F;1.0-forward...</span><br></pre></td></tr></table></figure>

<p>​    就是类似这样的byte数组，在每一次调用的时候，都产生了大概10M左右大小的数组，最终由于几百次的调用的同时这些数组对象 <strong>并不能回收掉</strong>，最终导致了内存的溢出。</p>
<p>​    这时候你可能会认为有人要来背锅了，然而工程师断定代码泄露不是个人编写的代码导致的。接着我们继续思考，不是开发人员造成的，排查代码确实没有看到明显会导致溢出的点，那么这是怎么回事呢？</p>
<p>​    进一步排查，发现是有一个对象存在长期的占用那就是：<code>org.apache.tomcat.util.threads.TaskThread</code>，从包名字就可以知道是Tomcat自己的线程，这意味着Tomcat在这个线程当中创建了数组并且没有被回收。</p>
<p>​    既然数组没有被回收也就意味着工作线程还在执行任务，按理来说工作线程执行任务通常都是很快就会完成的，<strong>为什么TaskThread会长期等待呢？</strong>这里再通过测试和分析发现每一个工作线程居然停留了<strong>4秒</strong>以上，我们都知道通常情况下一个请求都是在一秒以内完成的，而这里的线程居然停留了长达4秒，这里是一个问题点，另外这里还发现每一个工作线程就创建了2个10M的数组，导致数组也因为还在使用而无法释放，所以这里2个10M的数组又是怎么来的？这是第二个问题点， </p>
<p>​    通过配置文件的查找发现了下面的内容：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">max-http-header-size: 10000000</span><br></pre></td></tr></table></figure>

<p>​    就是这个东西导致了每次Http请求都会创建20M的数组内容。</p>
<p>​    这里小结一下上面的内容，其实就是说每一个工作线程都创建一个20M数组，意味着100个工作线程就是2000M的大小，并且2000M还无法回收。按照这个速度累积，一旦请求过多JVM就会立马崩溃。</p>
<h3 id="解决问题："><a href="#解决问题：" class="headerlink" title="解决问题："></a>解决问题：</h3><p>​    既然知道了是工作线程的问题，那么接下来就要着手解决为什么线程会停留4秒以上以及这个20M数组的来源，在接下来的排查中还发现日志中还有如下的内容：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Timeout Exception....</span><br></pre></td></tr></table></figure>

<p>​    日志大致内容就是RPC的请求出现了大量的连接超时，而连接超时的时间刚好是<strong>4秒</strong>！通过询问发现原来工程师设置了RPC的超时时间刚好也是4秒，真相大白了！在每一次的工作线程执行代码的时候，都会执行一次RPC的远程调用，而当RPC服务挂掉的时候，此时由于连接远程服务器迟迟得不到响应导致系统需要等待4秒才会释放线程，在等待的时候工作线程会占用这个请求的资源并且卡死在线程上等待结果，如果在同一时间有很多的请求就会出现百来个工作线程挂在自己的线程卡死并且等待响应的结果，最终由于堆内存占用过多的数组对象，无法再分配新的对象导致OOM！</p>
<p>​    知道了问题，下一步就是解决问题了，这里解决办法也比较简单，首先我们需要把超时的时间设置为<strong>1S</strong>，一旦RPC连接时间超过<strong>1S</strong>就立马释放资源，防止工作线程出现远程调用的长时间等待占用资源的问题，另外就是<code>max-http-header-size</code>这个参数可以适当的调整小一点，这样在每次调用的时候就不需要占用过大的数组导致资源利用紧张的问题了。</p>
<h2 id="RPC通信框架导致的内存溢出："><a href="#RPC通信框架导致的内存溢出：" class="headerlink" title="RPC通信框架导致的内存溢出："></a>RPC通信框架导致的内存溢出：</h2><h3 id="问题情况："><a href="#问题情况：" class="headerlink" title="问题情况："></a>问题情况：</h3><ol>
<li>A服务器进行了升级之后，B的远程服务器宕机了，查看日志发现了OOM的异常</li>
<li>出现了超过4G的数组分配动作，由于JVM的堆不可能放下这种对象，直接导致了OOM</li>
<li>发现这个对象是RPC内部使用的通信对象构建出来的数组。</li>
</ol>
<h3 id="案发现场："><a href="#案发现场：" class="headerlink" title="案发现场："></a>案发现场：</h3><p>​    系统上有两个服务，服务A和服务B，服务A和服务B之间使用RPC的通信方式，同时使用的序列化协议是<code>ProtoBuf</code>，在通信协议上统一封装的对象格式这里假设使用的是Request，同时在远程调用的时候序列化和反序列化的封装和解析都是自定义的，接着我们在拓展一下细节：</p>
<ol>
<li>首先在请求服务A的时候，需要对传输过来的对象进行序列化，这个序列化就是类似于把你的对象转为一个byte[]数组（字节流）</li>
<li>服务A接受请求并且通过RPC发送到远程服务器B之后，使用RPC通信规则对内容进行序列化转为byte[]，服务B接受之后使用反序列化把byte[]数组进行反序列化，拿到对象的内容进行逻辑处理。</li>
<li>这两个服务之间遵循了自定义的<strong>Request</strong>的对象格式进行通信，保证序列化和反序列化之后的对象格式和内容一致。</li>
</ol>
<p>​    那么问题是什么呢，问题很奇怪，当服务A进行升级之后，部署上去没有几分钟，<strong>发现服务B挂了！</strong>很奇怪，明明改的是服务A却是服务B挂了，经过日志分析，发现也是Byte[]数组太大导致溢出，这里阅读日志之后发现，居然分配了一个4G的数组……</p>
<h3 id="RPC类的框架规则"><a href="#RPC类的框架规则" class="headerlink" title="RPC类的框架规则"></a>RPC类的框架规则</h3><p>​    这里先不急着说明产生问题的原因，我们先补充一下RPC框架的通信规则理论：</p>
<p>​    一个RPC 的通信框架大致过程：试想一下为了让服务A的所有请求在远程服务B接受之后都能够处理，服务器两边的RPC框架肯定是要对所有的请求对象做<strong>统一规范</strong>的，比如RPC使用了<strong>ProtoBuf</strong>作为序列化的协议标准，同时使用固定的对象格式对于对象数据进行序列化和反序列化操作，这里假设服务A序列化使用Request对象进行定制序列化之后发送到服务B，而服务B自然需要使用对应的Request将服务A传来的序列化对象来反序列化。</p>
<p>​    这里就有一个问题了，如果服务A改动了Request对象的定制格式，比如通信使用<strong>Request A+C</strong>被序列化之后发送的到服务B了，服务B按照之前的Request解开之后发现自己解不开对象，于是会创建一个byte[] 数组来存放序列化的数据，让客户端自己去完成反序列化的操作。</p>
<h3 id="排查结果："><a href="#排查结果：" class="headerlink" title="排查结果："></a>排查结果：</h3><p>​    排查的结果就是<strong>服务A改了Request而m没有通知服务B修改对应的对象</strong>，导致反序列化失败并且新建了一个Byte[]数组来存放序列化的数据，而这个数组默认值刚刚好就设置了4G的大小！为什么要设置这么大的数组？开发人员说怕数组过小放不下，所以构建了一个4G的数组，保证无论A服务发送的对象如何大也不会影响到B。</p>
<h3 id="解决问题：-1"><a href="#解决问题：-1" class="headerlink" title="解决问题："></a>解决问题：</h3><p>​    很简单只要把这个反序列化失败之后创建数组的大小改小一点就行了，改成4M的大小基本足够应付大部分的情况。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>​    这一节主要讲述了分区的问题以及实际的案例中分区溢出的问题是如何排查的，可以看到虽然我们都十分清楚分区溢出是什么情况，但是到实际的案例中进行排查却又是五花八门的问题出现，希望通过案例讲解让更多的同学可以了解到JVM是如何进行问题排查，同时这里也可以发现，平时还是需要对于底层基础知识进行多积累，很多时候<strong>并不是学到的东西用不上，而是到了用上的时候你没学</strong>。所以平时多磨练一下自己的脑袋，遇到问题才不会手足无措。</p>
<h1 id="写在最后："><a href="#写在最后：" class="headerlink" title="写在最后："></a>写在最后：</h1><p>​    不知道为什么时候在方法区的溢出实际运行测试的时候个人的笔记本电脑死活不能溢出，即使设置了参数也是方法区不断的溢出，难道是我是AMD的CPU的问题？？？</p>
<h1 id="往期回顾："><a href="#往期回顾：" class="headerlink" title="往期回顾："></a>往期回顾：</h1><p>​    注意这里使用的是“有道云笔记”的链接，方便大家收藏和自我总结：</p>
<p>​    <span class="exturl" data-url="aHR0cDovL25vdGUueW91ZGFvLmNvbS9ub3Rlc2hhcmU/aWQ9MjRjYmQ1YmQxNGMyZDVmNDg0ZGRmMTQ1ZWI0OGZhNGMmc3ViPUVGNDYwREEyMkM2MjQzOUI4MkY4QzA1OEE4MUM3M0Qw" title="http://note.youdao.com/noteshare?id=24cbd5bd14c2d5f484ddf145eb48fa4c&sub=EF460DA22C62439B82F8C058A81C73D0">深入理解JVM - 阶段总结与回顾（二）<i class="fa fa-external-link"></i></span></p>
<p>​    <span class="exturl" data-url="aHR0cDovL25vdGUueW91ZGFvLmNvbS9ub3Rlc2hhcmU/aWQ9Y2M0MDM5MWI4NzYzYWE2MTkwYTlmNTZjM2QxOWE3OGEmc3ViPTgyRTJBMzZFMjM3MzQ1NDI4RDI5REQwNTYxMDM3RDY1" title="http://note.youdao.com/noteshare?id=cc40391b8763aa6190a9f56c3d19a78a&sub=82E2A36E237345428D29DD0561037D65">深入理解JVM - 案例实战<i class="fa fa-external-link"></i></span></p>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>阿东
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://whitestore.top/2022/02/20/yichu/" title="深入理解JVM - 分区是如何溢出的？">https://whitestore.top/2022/02/20/yichu/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLzQuMC96aC1DTg=="><i class="fa fa-fw fa-creative-commons"></i>BY-NC</span> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JVM/" rel="tag"># JVM</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/02/20/jvmshizhan/" rel="prev" title="深入理解JVM - 案例实战">
      <i class="fa fa-chevron-left"></i> 深入理解JVM - 案例实战
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/02/20/jvmyichu/" rel="next" title="深入理解JVM - 分区溢出实战">
      深入理解JVM - 分区溢出实战 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#深入理解JVM-分区是如何溢出的？"><span class="nav-number">1.</span> <span class="nav-text">深入理解JVM - 分区是如何溢出的？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">2.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#前文回顾："><span class="nav-number">3.</span> <span class="nav-text">前文回顾：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#概述："><span class="nav-number">4.</span> <span class="nav-text">概述：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分区结构图简介："><span class="nav-number">5.</span> <span class="nav-text">分区结构图简介：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#分区溢出模拟："><span class="nav-number">6.</span> <span class="nav-text">分区溢出模拟：</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#方法区："><span class="nav-number">6.1.</span> <span class="nav-text">方法区：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#虚拟机栈："><span class="nav-number">6.2.</span> <span class="nav-text">虚拟机栈：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#堆内存："><span class="nav-number">6.3.</span> <span class="nav-text">堆内存：</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#如何排查分区溢出问题？"><span class="nav-number">7.</span> <span class="nav-text">如何排查分区溢出问题？</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Tomcat出现OOM如何排查？"><span class="nav-number">7.1.</span> <span class="nav-text">Tomcat出现OOM如何排查？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#还原案发现场："><span class="nav-number">7.1.1.</span> <span class="nav-text">还原案发现场：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#简单了解Tomcat的底层原理"><span class="nav-number">7.1.2.</span> <span class="nav-text">简单了解Tomcat的底层原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内存快照分析："><span class="nav-number">7.1.3.</span> <span class="nav-text">内存快照分析：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#解决问题："><span class="nav-number">7.1.4.</span> <span class="nav-text">解决问题：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#RPC通信框架导致的内存溢出："><span class="nav-number">7.2.</span> <span class="nav-text">RPC通信框架导致的内存溢出：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#问题情况："><span class="nav-number">7.2.1.</span> <span class="nav-text">问题情况：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#案发现场："><span class="nav-number">7.2.2.</span> <span class="nav-text">案发现场：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RPC类的框架规则"><span class="nav-number">7.2.3.</span> <span class="nav-text">RPC类的框架规则</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#排查结果："><span class="nav-number">7.2.4.</span> <span class="nav-text">排查结果：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#解决问题：-1"><span class="nav-number">7.2.5.</span> <span class="nav-text">解决问题：</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">8.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#写在最后："><span class="nav-number">9.</span> <span class="nav-text">写在最后：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#往期回顾："><span class="nav-number">10.</span> <span class="nav-text">往期回顾：</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">阿东</p>
  <div class="site-description" itemprop="description">随遇而安</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">239</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">36</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lazyTimes"><i class="fa fa-fw fa-github"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjEwOTc0ODM1MDhAcXEuY29t" title="E-Mail → mailto:1097483508@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly93d3cuNTJwb2ppZS5jbi9ob21lLnBocD9tb2Q9c3BhY2UmdWlkPTE0OTc3MTgmZG89dGhyZWFkJnZpZXc9bWUmZnJvbT1zcGFjZQ==" title="https:&#x2F;&#x2F;www.52pojie.cn&#x2F;home.php?mod&#x3D;space&amp;uid&#x3D;1497718&amp;do&#x3D;thread&amp;view&#x3D;me&amp;from&#x3D;space">吾爱破解</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9qdWVqaW4uaW0vdXNlci8yOTk5MTIzNDUyNjI2MzY2" title="https:&#x2F;&#x2F;juejin.im&#x2F;user&#x2F;2999123452626366">掘金</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9zZWdtZW50ZmF1bHQuY29tL3UvbGF6eXRpbWVz" title="https:&#x2F;&#x2F;segmentfault.com&#x2F;u&#x2F;lazytimes">思否</span>
        </li>
    </ul>
  </div>

      </div>

      <div class="wechat_OA">
        <span>欢迎关注我的公众号</span>
        <br>
          <!-- 这里添加你的二维码图片 -->
        <img src ="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/wechat_channel.jpg">
      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">阿东</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">2m</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">29:50</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'qMUpEEvBgXaMDD1b0ftgi9xr-gzGzoHsz',
      appKey     : 'UCdfT4Rfih6MO6y8DI4fstf6',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
